//
//  BTRatingView.m
//  BaxTer
//
//  Created by wsj2015 on 16/10/13.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTRatingView.h"
#import "UITextView+PlaceHolder.h"
#import "UITextView+MaxLength.h"

@implementation BTRatingView

- (IBAction)confirmAction:(id)sender {
    
    if (self.confirmBlock) {
        self.confirmBlock(self.helpNess.value * 2,self.textView.text);
    }

}

- (void)setAbleToRate:(BOOL)ableToRate{
        _ableToRate = ableToRate;
    
    
        self.helpNess.userInteractionEnabled = ableToRate;
    if (ableToRate == NO) {
        self.titleL.text = @"您已经评过分了!您的评分是:";
        self.confirmBtn.userInteractionEnabled = YES;
    }
    
}
- (void)textViewDidChange:(UITextView *)textView{
    if (self.helpNess.value > 0 && self.textView.text.length > 0) {
        self.confirmBtn.enabled = YES;
    }else{
        self.confirmBtn.enabled = NO;
    }
    
}

+ (instancetype)ratingView{
    BTRatingView *ragingView =[[NSBundle mainBundle] loadNibNamed:@"BTRatingView" owner:nil options:0].lastObject;
    ragingView.textView.placeholder  =@"评论,100字以内";
    ragingView.textView.maxLength = 100;
    ragingView.textView.delegate = ragingView;
    ragingView.confirmBtn.enabled = NO;
    ragingView.confirmBtn.layer.cornerRadius = 4;
    ragingView.confirmBtn.layer.masksToBounds  = YES;
    ragingView.layer.cornerRadius = 8;
    ragingView.layer.masksToBounds =YES;
    [ragingView.helpNess addObserver:ragingView
                          forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
  
    
    return ragingView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  
    if ([object isEqual:self.helpNess]) {
        if ([keyPath isEqualToString:@"value"]) {
            NSNumber *v =  change[@"new"];
            if (v.floatValue <=0) {
                v = @(0);
            }
          
            
            
        }
    }
   
    if (self.helpNess.value > 0 && self.textView.text.length > 0) {
        self.confirmBtn.enabled = YES;
    }else{
        self.confirmBtn.enabled = NO;
    }
   
   
}
- (void)dealloc{
    [self.helpNess removeObserver:self forKeyPath:@"value"];
   
}
@end
